<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

</head>

<body>
  <p>js分隔数组</p>
  <script>
    // 方法一
    function formatNumber_one(num) {
      let index, result, s, startLen;
      s = num.toString();
      result = '';
      startLen = s.length % 3;
      if (!startLen) {
        startLen = 3;
      }
      index = 0;
      result += s.substr(0, startLen);
      index += startLen;
      while (index < s.length) {
        result += "," + s.substr(index, 3);
        index += 3;
      }
      return result;
    };
    console.log(formatNumber_one(1234567));

    // 方法二
    function formatNumber_two(num, n) {
      var num = num.toString(),
        remain_num = num.slice(0, num.length % n)
      return remain_num + ',' + num.slice(num.length % n).match(new RegExp('\\d{' + n + '}', 'g')).join(',')
    }
    console.log(formatNumber_two(1234567, 3));

    // 方法三
    function formatNumber_three(num, n) {
      return num.toString().replace(new RegExp('\\B(?=(\\d{' + n + '})+(?!\\d))', 'g'), ',')
    }
    console.log(formatNumber_three(1234567, 3));

    // 方法四
    function formatNumber_four(num) {
      return num.toLocaleString()
    }
    console.log(formatNumber_four(1234567));
  </script>
</body>

</html>